<template>
    <Pop :show="show" :is-close="true" :is-back="false" :is-title="false" paddingType="spadding" @back="onBack"
        @close="onHide">
        <div class="sub-title">
            <!-- 邮箱验证 -->
            {{ $t("message.RegisterVerify.verify") }}
        </div>
        <div class="top-tip c-title-4">
            <!-- 请输入您在邮箱 -->
            {{ $t("message.RegisterVerify.captcha") }}
            {{ account.saveEmail }}
            <!-- 收到的6位验证码，30分钟内有效 -->
            {{ $t("message.RegisterVerify.captcha2") }}
        </div>
        <v-form validate-on="submit lazy" class="form-width">
            <div class="sub-tip">
                <!-- 邮箱验证码 -->
                {{ $t("message.RegisterVerify.emailCode") }}
            </div>
            <!-- <v-text-field clearable class="j-input" v-model="code" :rules="codeRules" placeholder="请输入您的邮箱驗證碼"
                :loading="false" color="#15181D" bg-color="#15181D">
                <span class="code-tip had" v-if="hasSend">验证码已发送</span>
                <span class="code-tip" v-else @click="onSend">获取验证码</span>
            </v-text-field> -->

            <div class="ips">
                <JInput v-model="code" :clear="false" :err="emailErro"
                    :placeholder="$t('message.RegisterVerify.placeholder')"></JInput>
                <div class="code-tip had" v-if="countdown > 0">
                    <!-- 验证码已发送 -->
                    <!-- {{ $t("message.RegisterVerify.captchaSend") }} -->
                    <!-- {{$t("message.RegisterVerify_.j").replace("@", countdown + "")}} -->
                    {{ countdown }}s
                </div>
                <div class="code-tip" v-else @click="onSend">
                    <!-- 获取验证码 -->
                    {{ $t("message.RegisterVerify.getverify") }}
                </div>
            </div>

            <div id="cfts1"></div>


            <!-- <v-btn class="me-4 submit-btn" color="primary" type="submit"> 提交 </v-btn> -->
            <JButton :disabled="!canClick" class="me-4 submit-btn" :label="$t('message.RegisterVerify.submit')"
                @click="onSubmit"></JButton>
        </v-form>
    </Pop>
</template>

<script lang="ts" setup>
import { URL_REGISTER, URL_EMAIL_CODE, URL_BIND_EMAIL, URL_AI_VERIFY } from "@/comm/api";
import { get, post } from "@/comm/request";
import Pop from "@/components/pop/index.vue";
import { toast } from "@/components/toast/toast";
import { useAccount } from "@/stores/account";
import { useUser } from "@/stores/user";
import JInput from "@/components/j-input/index.vue";
import JButton from "@/components/j-button/index.vue";
import { ref, onMounted, watch } from "vue";
import i18n from "@/locals";
import { useCountdown } from "./countDown";
import { LoginCall } from "@/comm/Heap";
import { Notify } from "@/components/y-notify/script";
import { useScale } from "./hooks/scales";
const user = useUser();
// const scale = useScale();
const account = useAccount();
const hasSend = ref(false);
const code = ref("");
const canClick = ref(true);
// const sec = ref(0);
const { countStart, countdown } = useCountdown();
let tokens = ""
const emailErro = ref("")
const onBack = () => {
    // account.changePopRegister(true);
    // account.changePopRegisterVerify(false);
    hasSend.value = false;
    code.value = "";
    history.back();
};

const props = defineProps({
    show: Boolean
})

const emit = defineEmits(["close"])

watch(() => props.show, (val) => {
    if (val) {
        changeSize();
    }
})

const changeSize = () => {
    let dom: any = document.querySelector(".mask-box");
    if (dom) {
        if (window.innerWidth && dom.clientWidth) {
            let n = window.innerWidth / dom.clientWidth * 0.92;
            dom.style.transform = `scale(${n})`;
            return true;
        }
    }
    setTimeout(changeSize, 90);
}

onMounted(() => {

})

const onHide = () => {
    // account.changePopRegisterVerify(false);
    emit("close")
}

watch(() => account.popRegisterVerify, (v) => {
    if (v) {
        emailErro.value = ""
        tokens = "";
    }
    else {
        // console.log("remove yyyy");
        (window as any).turnstile?.remove();
    }
});

const codeRules = ref([
    (value: string) => {
        if (value) return true;
        return "code is requred.";
    },
    (value: string) => {
        if (value.length === 6) return true;
        return "code must be valid.";
    }
]);

const onBindEmail = () => {
    emailErro.value = ''
    post(
        URL_BIND_EMAIL,
        {
            email: account.email,
            dynamicCode: code.value,
            recommendCode: account.recommendCode,
            thirdPartyId: ""
        },
        true
    )
        .then(async (res: any) => {
            console.log(res, typeof res);
            if (res.code == 200) {
                // toast("绑定成功");
                // toast(i18n.global.t("message.RegisterVerify.success"));
                Notify.alert(i18n.global.t("message.RegisterVerify.success"));
                onHide();
            } else {
                emailErro.value = res.info;
                // toast(res.info);
            }
            // account.changePopRegisterVerify(false);
        })
        .catch((err: any) => {
            console.error('邮箱绑定失败！！！！！！！！！', err);
            // toast("绑定失敗");
            // toast(i18n.global.t("message.RegisterVerify.error"));
            Notify.alert(i18n.global.t("message.RegisterVerify.error"), "warning", 3500)
        })
        .finally(() => {
            hasSend.value = false;
        });
};

const onRegister = () => {
    console.log('注册邮箱', account.recommendCode)
    post(
        URL_REGISTER,
        {
            email: account.email,
            dynamicCode: code.value,
            recommendCode: account.recommendCode,
            thirdPartyId: "",
            verifyCode: tokens
        },
        true, 1
    )
        .then(async (res: any) => {
            console.log(res, typeof res);
            if (res.code == 200) {
                localStorage.setItem("token", res.data.token);

                let err = await user.getUserInfo();
                console.log('获取个人信息', err)
                if (!err) {
                    await user.getRegisterEnergyMax();
                    LoginCall.I.Next(true);
                    account.changePopRegisterSuccess(true);
                    account.changePopRegisterVerify(false);
                    // location.href = "/reward";
                    localStorage.setItem("willJump", "1");
                    location.href = "/";
                }
            } else {
                // toast(res.info);
                // Notify.alert(res.info, "warning", 3500)
                emailErro.value = res.info;
            }
            // account.changePopRegisterVerify(false);
        })
        .catch((err: any) => {
            console.error('注册失败！！！！', err);
            // toast("注冊失敗");
            Notify.alert("message.RegisterVerify.error_", "warning", 3500)
            // toast(i18n.global.t("message.RegisterVerify.error_"));
        })
        .finally(() => {
            hasSend.value = false;
            tokens = ""
        });
};

const aiCheck = () => {
    console.log("ai code")
    return new Promise<string>(resolve => {
        let turnstile = (window as any).turnstile;
        if (turnstile) {
            turnstile.remove();
            turnstile.render("#cfts1", {
                sitekey: "0x4AAAAAAAOzWQkEw2f6U-bV",
                language: "en",
                callback: function (token: any) {
                    console.log(`Challenge Success ${token}`);
                    tokens = token;
                    resolve(token);
                }
            });
        }

    })
}

const onSubmit = async () => {
    canClick.value = false;
    setTimeout(() => {
        canClick.value = true;
    }, 2000);
    emailErro.value = ''
    if (!code.value) {
        // toast(i18n.global.t("message.RegisterVerify.code"));
        emailErro.value = i18n.global.t("message.RegisterVerify.code")
        return;
    }
    if (code.value.length != 6) {
        // toast(i18n.global.t("message.RegisterVerify.code_"));
        emailErro.value = i18n.global.t("message.RegisterVerify.code_")
        return;
    }
    console.log(code.value, "submit register");
    // if (!location.href.includes("view.io")) {
    //     tokens = "test";
    // }
    if (account.isBindEmail) {
        onBindEmail();
        return;
    }

    if (!tokens) {
        if (!location.href.includes("view.io")) {
            tokens = "test";
        }
        else {
            tokens = await aiCheck();
        }
        // if(location.href.includes("debug=1")){
        //     tokens = "test";
        // }
        // else{
        //     tokens = await aiCheck();
        // }

        let res: any = await post(URL_AI_VERIFY,
            {
                email: account.email,
                dynamicCode: code.value,
                recommendCode: account.recommendCode,
                thirdPartyId: "",
                verifyToken: tokens
            },
            true, 1);
        if (res.code == 200) {
            tokens = res.data
            onRegister();
        }
        else {
            toast(res.info);
            tokens = "";
        }
        return;
    }

    onRegister();
};

const onSend = async () => {
    hasSend.value = true;
    countStart();
    post(URL_EMAIL_CODE, {
        msgId: user.noEmail ? 105 : 101,
        email: account.email,
    })
        .then((res: any) => {
            console.log(res, typeof res);
        })
        .catch((err: any) => {
            console.log(err, "err");
        });
    
    console.log("-----send ai-----");
    tokens = await aiCheck();

};
</script>

<style lang="less" scoped>
@import url("./index.less");

.form-width {
    width: 400px;
}

.ips {
    position: relative;
}

.code-tip {
    position: absolute;
    font-size: 12px;
    right: 10px;
    bottom: 0;
    top: 0;
    margin: auto;
    color: var(--main);
    cursor: pointer;
    display: flex;
    align-items: center;
    z-index: 1;
}

.sub-tip {
    font-size: 14px;
    color: var(--sub);
}

.top-tip {
    margin-top: 12px;
    margin-bottom: 42px;
    color: var(--sub);
    width: 400px;
}

.had {
    color: var(--sub);
}

.submit-btn {
    margin-top: 48px;
    width: 100%;
    margin-bottom: 20px;
}

.sub-title {
    font-size: 28px;
    margin-bottom: 50px;
    color: #fff;
}

#cfts1 {
    text-align: center;
    margin-top: 30px;

    iframe {
        width: 90%;
    }
}
</style>
